package com.fysports.framework.kit.security;

import java.security.MessageDigest;


/**
 * MD5算法
 * Created by konbluesky
 * Date : 14-7-31 下午4:00
 * Project : JdmData_WebServer
 */
public class MD5Kit {
    /**
     * 使用MD5加密字节数组，加密后转换成十六进制的字符串。
     *
     * @param str 要加密的字节
     * @return 经加密转换后形成的三十二位字符串
     */
    public static String get32MD5(String str) {
        if (str == null)
            str = "";

        StringBuffer sb = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte byEncrypt[] = md.digest(str.getBytes());

            for (int i = 0; i < byEncrypt.length; i++) {
                sb.append(Integer.toHexString(byEncrypt[i] & 0xFFFF));
            }
        }
        catch (Exception ex) {
        }
        return sb.toString();
    }


    /**
     * 将字符串加密为十六位的MD5密码
     *
     * @param str 要加密的字符串
     * @return 经加密转换后形成的十六位的字符串
     */
    public static String get16MD5(String str) {
        StringBuffer sb = new StringBuffer();
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        byte[] strTemp = str.getBytes();
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            byte byEncrypt[] = md.digest(strTemp);
            for (int i = 0; i < byEncrypt.length; i++) {
                byte byte0 = byEncrypt[i];
                sb.append(hexDigits[byte0 >>> 4 & 0xf]);
                sb.append(hexDigits[byte0 & 0xf]);
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            sb.append("");
        }
        return sb.toString();
    }


    public static void main(String[] args) {
        System.out.println(MD5Kit.get16MD5("123"));
        System.out.println(MD5Kit.get32MD5("123456"));
    }
}
